package com.baidu.manager.modules.sys.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.baidu.manager.modules.sys.entity.Account;
import com.baidu.manager.modules.sys.entity.SearchInfo;

public class HttpUtil {
	
	public static String formAccount(Object object) {
		Account account = (Account) object;
		return "account="+account.getAccount()+"&password="+account.getPassword();
	}
	
	public static String formSearchInfo(Object object) {
		SearchInfo searchInfo = (SearchInfo) object;
		return "name=" + "" + "&mobile=" + "" + "&id_card_no="
				+ "" + "&register_client_origin=" + ""
				+ "&start_date=" + "" + "&end_state=" + "" + "&status="
				+ "" + "&page=" + searchInfo.getPage() + "&limit=" + searchInfo.getLimit()
				+ "&order=" + "";
	}

	/**
	 * post提交流形式的json数据
	 * 
	 * @param urlStr
	 *            访问地址
	 * @param object
	 *            提交json格式数据的原始JavaBean
	 * @return 响应结果（json串）
	 */
	public static String postJsonByJavaObject(String urlStr, Object object) {
		StringBuffer sb = new StringBuffer(1024);
		try {
			// 创建连接
			URL url = new URL(urlStr);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connection.setRequestProperty("token", "5044dae0cd818c06cad5c99237f76674");

			connection.connect();

			// POST请求
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//			String jsonString = JSONObject.toJSONString(object);
			
			out.writeBytes(formSearchInfo(object));
//			out.writeBytes("account="+"Testing"+"&password="+"testing");
			out.flush();
			out.close();

			// 读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String lines;
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}

			// System.out.println(sb);
			reader.close();
			// 断开连接
			connection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();

	}
}
